`
2 if [[ "${EUID}" -eq "0" ]]; then
return 0
else
return 1
fi
}
3 is_root=$(check_if_root)
4 if [[ "${is_root}" -eq "0" ]]; then
echo "user is root!"
else
echo "user is not root!"
fi
Listing 2-8
An if condition to test whether a function returned true or false
We define the check_if_root function 1. Within this function, we use an
if condition with an integer comparison test 2, accessing the environment
variable EUID to get the effective running user’s ID and checking whether it
equals 0. If so, the user is root, and the function returns 0; if not, it returns 1. Next,
we call the function and assign the result returned to the variable is_root 3.
Then we use another integer comparison test to determine this value 4. This code
is available at https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/check_root_function.sh.
Bash scripts that perform privileged actions often check whether the user is
root before attempting to install software, create users, delete groups, and so on.
Attempting to perform privileged actions on Linux without the necessary
privileges will result in errors, so this check helps handle these cases.
Accepting Arguments
In the previous chapter, we covered the passing of arguments to commands on
the command line. Functions can also take arguments using the same syntax. For
example, the function in Listing 2-9 prints the first three arguments it receives:
#!/bin/bash
print_args(){
echo "first: ${1}, second: ${2}, third: ${3}"
}
1 print_args No Starch Press
Listing 2-9
A function with arguments
To call a function with arguments, simply enter its name and the arguments
separated by spaces 1. Save this script as function_with_args.sh and run it:
$ chmod u+x function_with_args.sh
$ ./function_with_args.sh
first: No, second: Starch, third: Press
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks